import { useEffect, useRef, useState } from "react";
import { generateNumber } from "../utils/tool";
import { Button, Checkbox, Space, message } from "antd";
import { AudioOutlined, EyeOutlined, QuestionCircleFilled, QuestionCircleOutlined, SearchOutlined, SoundOutlined } from "@ant-design/icons";
import pinyinUtil from "pinyin/lib/pinyin-web.js";
import { saveToFiles } from "./tool";

enum RecordStatus {
    开 = 1,
    关 = 0
}
export default function Read(props: { defaultArr: Array<{ pinyin: Array<string>, wenzi: string }>, unit: number }) {
    const { defaultArr, unit } = props;
    const recognitionRef: any = useRef()

    const [state, _setState] = useState<{
        arr: Array<{ pinyin: Array<string>, wenzi: string }>,
        result: Array<{ voice?: Array<string>, wenzi: string, correct?: boolean }>,
        current: null | { wenzi: string, pinyinWithoutShd: string, pinyin: Array<string> },
        status: RecordStatus,
        view: boolean,
    }>({
        arr: defaultArr,
        result: [],
        current: null,
        status: RecordStatus.关,
        view: false
    });
    const setState = (params: { [key: string]: any }) => {
        _setState((_state) => ({ ..._state, ...params }));
    };
    const { arr, current, status, result,view } = state;

    function printWord(sound?: string) {
        console.log(sound, current)
        let prev, next;
        if (sound && current) {
            let voice = ([]).concat(...pinyinUtil(sound, {
                style: 'normal'
            }) as any).join('')
            prev = {
                ...current,
                voice: voice,
                correct: voice === current.pinyinWithoutShd
            }
        }
        if (arr.length) {
            let num = generateNumber(1, arr.length);
            let text = arr[num - 1];
            let _arr = [...arr]
            _arr.splice(num - 1, 1);
            next = {
                arr: _arr,
                current: {
                    ...text,
                    pinyinWithoutShd: ([]).concat(...pinyinUtil(text.wenzi, {
                        style: 'normal'
                    }) as any).join('')
                },
            }
        }
        setState({
            view: false,
            result: prev ? [...result, prev] : result,
            ...next
            // status: RecordStatus.开
        })
    }

    // function(){}
    useEffect(() => {
        //设置页面加载完成
        // 检查浏览器是否支持语音识别API
        if (!('webkitSpeechRecognition' in window)) {
            alert('您的浏览器不支持语音识别服务');
        } else {
            // 创建一个语音识别的新实例
            let recognition = new (window as any).webkitSpeechRecognition();
            recognitionRef.current = recognition;

            // 设置语音识别服务的语言，这里设置为中文
            recognition.lang = 'cmn-Hans-CN';

            // 开始语音识别
            recognition.continuous = false;
            // recognition.interimResults = false; // 是否返回临时结果


            // 当语音识别服务发送结果时，会触发这个事件
            recognition.onresult = function (event: any) {

                // 获取并输出识别结果
                let text = event.results[0][0].transcript;

                console.log('你说了：', text);
                recognitionRef.current.stop()
                printWord(text)
            };

            // 当语音识别服务遇到错误时，会触发这个事件
            recognition.onerror = function (event: any) {
                console.error('发生错误：', event.error);
                message.error('没有检测到声音！')
            };

            recognition.onend = function (e: any) {
                setState({
                    status: RecordStatus.关
                })
                console.error('录音结束', e);

            }
        }
    }, [current, arr, result, status]);
    useEffect(() => {
        printWord()
    }, [])
    if (result.length === defaultArr.length) {
        return <div>
            <div>
                <Space>
                    <div style={{ fontSize: '20px', margin: '1rem' }}>
                        测试结果
                    </div>
                    <Button type="link" onClick={() => {
                        // saveToFiles()
                        fetch('/api/discovery?unit=' + unit, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(result)
                        })
                    }}>保存</Button>
                </Space>
            </div>
            <Checkbox.Group value={result.filter(item => item.correct).map(item => item.wenzi)} onChange={(values) => {
                setState({
                    result: result.map(item => {
                        return {
                            ...item,
                            correct: values.includes(item.wenzi)
                        }
                    })
                })
            }}>
                <Space wrap>
                    {
                        result.map((item, key) => {
                            return <Checkbox value={item.wenzi} key={key}>
                                <span>{item.voice}</span>
                                <span>{item.wenzi}</span>
                            </Checkbox>
                        })
                    }
                </Space>
            </Checkbox.Group>

        </div>
    }
    return <>
        <Space style={{ fontSize: '48px', margin: '1rem 0 1rem 0' }}>
            {
                current?.wenzi.split('').map((item, k) => {
                    return <span key={k}>
                        <div style={{height: '60px'}}>{ view && current.pinyin[k]}</div>
                        {
                            item
                        }
                    </span>
                })
            }

        </Space>
        <div></div>
        {
            status == RecordStatus.开 ? <Space><Button type="link" icon={<SoundOutlined style={{ fontSize: '24px' }} />}></Button> <span style={{ color: 'rgba(0,0,0, 0.45)' }}>正在录音...</span></Space> :
                <Space>
                    <Button icon={<AudioOutlined />} type="link" onClick={() => {
                        setState({
                            status: RecordStatus.开
                        })
                        setTimeout(() => {
                            recognitionRef.current.start()
                        }, 1);
                    }}>开始录音</Button>
                    <Button icon={<SearchOutlined />} type="link"
                        onClick={() => {
                            setState({
                                view: true
                            })
                        }}
                    >查看</Button>
                </Space>
        }
    </>
}
